package cc.vv.baselibrary.util.router;

import android.app.Activity;

import java.util.concurrent.ConcurrentHashMap;

import cc.vv.lkrouter.inter.RouterInter;
import cc.vv.lkrouter.router.RouterActivity;

/**
 * Class类路由注册工具类
 * Created by sun.li on 2018/7/6.
 *
 * @author sun.li
 */

public class RouterClassUtil implements RouterInter<Object,Class<? extends Object>>{

    private ConcurrentHashMap<String, Class<? extends Object>> mClassZ = new ConcurrentHashMap();
    private ConcurrentHashMap<String, Object> mClassA = new ConcurrentHashMap();
    private static RouterClassUtil mInstance;

    private RouterClassUtil() {
    }

    public static RouterClassUtil getInstance() {
        if(null == mInstance) {
            synchronized(RouterActivity.class) {
                if(null == mInstance) {
                    mInstance = new RouterClassUtil();
                }
            }
        }
        return mInstance;
    }

    @Override
    public void routerT(String key, Object obj) {
        Object cacheActivity = this.mClassA.get(key);
        if(null == cacheActivity || obj != cacheActivity) {
            this.mClassA.put(key, obj);
        }
    }

    @Override
    public Object invokT(String key) {
        return this.mClassA.get(key);
    }

    @Override
    public void routerV(String key, Class<?> aClass) {
        Class cacheClass = this.mClassZ.get(key);
        if(null == cacheClass || aClass != cacheClass) {
            this.mClassZ.put(key, aClass);
        }
    }

    @Override
    public Class<? extends Object> invokV(String key) {
        return this.mClassZ.get(key);
    }

    /** 获取Object对象*/
    public Object getObject(String key){
        Object object = invokT(key);
        if(null == object){
            try {
                Class<? extends Object> aClass = invokV(key);
                if(null != aClass) {
                    object = aClass.newInstance();//通过Class对象实例化当前对象
                }
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return object;
    }
}
